package com.xxlie.shop.service.impl;

import com.xxlie.auth.domain.Role;
import com.xxlie.auth.domain.User;
import com.xxlie.core.model.Page;
import com.xxlie.shop.domain.Feedback;
import com.xxlie.shop.repository.FeedbackRepository;
import com.xxlie.shop.service.FeedbackService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class FeedbackServiceImpl implements FeedbackService {
    @Autowired
    FeedbackRepository feedbackRepository;

    @Override
    public Feedback findOne(Long id) {
        return this.feedbackRepository.findOne(id);
    }

    @Override
    public Feedback save(Feedback feedback) {
        return this.feedbackRepository.save(feedback);
    }

    @Override
    public void update(Feedback feedback) {
        this.feedbackRepository.save(feedback);
    }

    @Override
    public void delete(Long id) {
        this.feedbackRepository.deleteById(id);
    }

    @Override
    public Page<Feedback> findAll(Page<Feedback> page, Feedback feedback) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Feedback> dictPage = feedbackRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();

            if (feedback != null){
                //搜索内容
                if(StringUtils.isNotEmpty(feedback.getBody())){
                    predicates.add(builder.like(root.get("body"), "%" + feedback.getBody() + "%"));
                }
                //搜索ID
                if(feedback.getId() != null && feedback.getId() != 0){
                    predicates.add(builder.equal(root.get("id"), feedback.getId()));
                }
            }
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<>(dictPage);
    }

    @Override
    public List<Feedback> findAllByUserAndCreateDateGreaterThanEqual(User user, Date createStartDate) {
        return this.feedbackRepository.findAllByUserAndCreateDateGreaterThanEqual(user, createStartDate);
    }
}